//
// Created by 廖海龙 on 2025/4/9.
//
#define LOG_TAG "Victor"

#include "JniInit.hpp"
#include <string>

#include "framework/log/Logger.hpp"
#include "framework/net/HelloVideoCacheServer.hpp"

jlong nativeInitHelloVideoCache(JNIEnv *env, jobject thiz) {
//    jobject globalObj = env->NewGlobalRef(thiz);

    auto native = new HelloVideoCacheServer();
    return reinterpret_cast<jlong>(native);
}


void nativeSetConfig(JNIEnv *env, jobject thiz, jlong ptr, jobject c) {
    auto native = reinterpret_cast<HelloVideoCacheServer *>(ptr);
    HelloCacheConfig config;

    // 获取 Java 类
    jclass cls = env->GetObjectClass(c);

    // int defaultPort
    jfieldID fidPort = env->GetFieldID(cls, "defaultPort", "I");
    config.defaultPort = env->GetIntField(c, fidPort);

    // String cacheDir
    jfieldID fidCacheDir = env->GetFieldID(cls, "cacheDir", "Ljava/lang/String;");
    jstring jCacheDir = (jstring)env->GetObjectField(c, fidCacheDir);

    if (jCacheDir != nullptr) {
        const char* nativeCacheDir = env->GetStringUTFChars(jCacheDir, nullptr);
        config.cacheDir = nativeCacheDir;
        env->ReleaseStringUTFChars(jCacheDir, nativeCacheDir);
    }

    return native->setConfig(config);
}

void nativeStart(JNIEnv *env, jobject thiz, jlong ptr) {
    auto native = reinterpret_cast<HelloVideoCacheServer *>(ptr);
    return native->start();
}

void nativeStop(JNIEnv *env, jobject thiz, jlong ptr) {
    auto native = reinterpret_cast<HelloVideoCacheServer *>(ptr);
    native->stop();
}

void nativeReleaseHelloVideoCache(JNIEnv *env, jobject thiz, jlong ptr) {
    auto native = reinterpret_cast<HelloVideoCacheServer *>(ptr);
    delete native;
}

static JNINativeMethod jniMethods[] = {
        {"nativeInit",      "()J",                                                 (void *) nativeInitHelloVideoCache},
        {"nativeSetConfig", "(JLorg/liaohailong/library/HelloVideoCacheConfig;)V", (void *) nativeSetConfig},
        {"nativeStart",     "(J)V",                                                (void *) nativeStart},
        {"nativeStop",      "(J)V",                                                (void *) nativeStop},
        {"nativeRelease",   "(J)V",                                                (void *) nativeReleaseHelloVideoCache},
};


int register_hello_video_cache(JNIEnv *env) {

    jclass clz = env->FindClass("org/liaohailong/library/HelloVideoCache");
    if (clz == nullptr) {
        return false;
    }

    int num = ((int) sizeof(jniMethods) / sizeof(jniMethods[0]));
    jint status = env->RegisterNatives(clz, jniMethods, num);
    if (status < JNI_OK) {
        Logger(LOG_TAG).i("RegisterNatives failure");
    }

    env->DeleteLocalRef(clz);

    return status == JNI_OK;
}